
<?php 
	    $id = Zend_Controller_Front::getInstance()->getRequest()->getParam('id', 0);
		$order = OrdersPeer::getInstance()->find($id)->current();
		if (!$order) {
			$order = OrdersPeer::getInstance()->createRow();
		}
		$delivery = $order->getDeliveryRowByDeliveryId();
		if (!$delivery) {
			$delivery = DeliveryPeer::getInstance()->createRow();
		}
		$unverified = OrdersService::getInstance()->getOrderStatusByKey(OrdersService::STATUS_ORDER_UNVERIFIED);
		$placed = OrdersService::getInstance()->getOrderStatusByKey(OrdersService::STATUS_ORDER_PLACED);
?>

    <fieldset>
	<legend>Состав заказа</legend>
	<table cellspacing=0 cellpadding=0 width="100%" class="orderedit listorder">
	    <thead>
		<tr>
		    <td width="10%" class="td2">Код товара</td>
		    <td width="50%" class="td1">Наименование</td>
		    <td width="10%" class="td2">Количество</td>
		    <td width="10%" class="td2">Цена</td>
		    <td width="10%" class="td2">Сумма</td>
		    <td width="5%" class="td2">Наличие</td>
		    <td width="5%" class="td2">Опции</td>
		</tr>
	    </thead>
	    <tbody id="product_list">
	    <?php 
	    if ($order->isProductCompositionModifiedAvailable()) {
	    ?>
	    <tr>
		    <td class="td2">
		    	<input type="text" id="product_id" style="width:40px;" autocomplete="off" class="crud_form_suggest" />
		    	<div class="suggest_result" style="display:none;"></div>
		    </td>
		    <td class="td1">
		    	<input type="text" id="product_name" style="width:150px;" autocomplete="off" class="crud_form_suggest" />
		    	<div class="suggest_result" style="display:none;"></div>
		    </td>
		    <td class="td2"><input type="text" id="product_count" style="width:20px;" class="product_callcenter_count_add"/></td>
		    <td class="td2" id="add_product_price">&nbsp;</td>
		    <td class="td2">&nbsp;</td>
		    <td class="td2" id="add_product_count">&nbsp;</td>
		    <td class="td2">
				<a href="#" title="Добавить" style="color:green;" id="product_add">=></a>
		    </td>
		</tr>
	    <?php
	    }
	    	$globalCount = 0;
	    	$globalCost = 0;
	    	if ($order->getId()) {
	    		$rowset = $order->getOrder2productRowsetByOrderId();
				$dis4prods = CouponService::getInstance()->getProductsDiscountByDb($order);
				foreach ($rowset as $order2product) {
					$product = $order2product->getProductRowByProductId();
					if (!$product) {
						continue;
					}
					$productPrice = $order2product->getPrice();
					if (isset($dis4prods[$product->getId()])){
						$productPrice -= $dis4prods[$product->getId()] * $productPrice / 100;
					}
					$sum = $productPrice * $order2product->getCount();
			    	$globalCost += $sum;
			    	$globalCount += $order2product->getCount();
			    	
			    	$deleteString = "<a href='#' style='color:red;' class='product_delete'>х</a>";
			    	if (!$order->isProductCompositionModifiedAvailable()) {
			    		$deleteString = '';
			    	}
			    	
			    	if ($order->isProductCompositionModifiedAvailable()) {
			    		$countString = "<input 
								style='width:20px;' 
								type='text' 
								class='product_count_input' 
								name='product_callcenter_count_edit[{$product->getId()}]' 
								value='{$order2product->getCount()}' />";
			    	} else {
						$countString = $order2product->getCount();
				    	if ($order2product->getDesiredCount() != $order2product->getCount()) {
				    		$countString = "<span style='color: red; font-weight: bold;'>$countString/{$order2product->getDesiredCount()}</span>";
				    	}
			    	}
			    	
					echo "<tr>
					    <td class='td2 product_added_id'>{$product->getInternalId()}</td>
			
					    <td class='td1'>{$product->getName()}</td>
					    <td class='td2 product_count' count='{$order2product->getCount()}'>$countString</td>
					    <td class='td2 product_price'>$productPrice</td>
					    <td class='td2 product_sum'>$sum</td>
					    <td class='td2'>{$product->getCount()}</td>
					    <td class='td2'>
							$deleteString
					    </td>
					</tr>";
			    }
	    	}
	    	
	    	$request = Zend_Controller_Front::getInstance()->getRequest();
	    	$newId = $request->getParam('product_callcenter_id');
	    	$newCount = $request->getParam('product_callcenter_count');
			//die(count($newId));
	    	if ($newId) {
		    	foreach ($newId as $key => $value) {
		    		if (!$value || !$newCount[$key]) continue;
		    		$product = ProductPeer::getInstance()->findByInternalId($value)->current();

		    		$globalCount += $newCount[$key];
		    		$sum = $product->getPrice() * $newCount[$key];
		    		$globalCost += $sum;
					echo "<tr>
						<td class='td2 product_added_id'>{$product->getInternalId()}</td>
						<td class='td1'>{$product->getName()}</td>
						<td class='td2 product_count' count='{$newCount[$key]}'>
							<input 
								style='width:20px;' 
								type='text' 
								class='product_count_input' 
								name='product_callcenter_count[]' 
								value='{$newCount[$key]}' />
						</td>
						<td class='td2 product_price'>{$product->getPrice()}</td>
						<td class='td2 product_sum'>$sum</td>
						<td class='td2'>{$product->getCount()}</td>
						<td class='td2'>
							<a href='#' class='product_delete' style='color:red;'>х</a>
							<input type='hidden' class='product_id_input' name='product_callcenter_id[]' value='{$product->getInternalId()}' />
						</td>
					</tr>";
		    	}
	    	}

	    ?>
	    
	    </tbody>
	    <tfoot>
	    <tr>
		    <td class="td2">&nbsp;</td>
		    <td class="td1">Доставка</td>
		    <td class="td2">&nbsp;</td>

		    <td class="td2">&nbsp;</td>
		    <td class="td2" id="product_delivery_sum">
		    <?php


				if($delivery->getCity() && $order->getTotalCost() && $order->getWeight()){
						$params = array("city"=>$delivery->getCity(),
						"in_city"=>$delivery->getInMkad(),
						"sum"=>$order->getTotalCost(),
						"weight"=> $order->getWeight()
						);
					if($order->getOrderStatusId() == $placed->getId() || $order->getOrderStatusId() == $unverified->getId()){
						$deliveryCost = DeliveryService::getInstance()->getDeliveryCost($params);
					}else{
						$deliveryCost = (int)$order->getDeliveryCost();
					}
					echo $deliveryCost;
				}else{
					$deliveryCost = 0;
					echo $deliveryCost;
				}
		    ?>
		    </td>
		    <td class="td2">&nbsp;</td>
		    <td class="td2">&nbsp;</td>
	    </tr>
		<tr>
		    <td class="td2">&nbsp;</td>
		    <td class="td1">Всего</td>
		    <td class="td2" id="product_count_total">
		    	<?php
		    		echo $globalCount;
		    	?>
		    </td>

		    <td class="td2">&nbsp;</td>
		    <td class="td2" id="product_price_total">
		    	<?php
		    		echo $globalCost; 
		    	?>
		    </td>
		    <td class="td2">&nbsp;</td>
		    <td class="td2">&nbsp;</td>
		</tr>
		<tr>
		    <td class="td2">&nbsp;</td>
		    <td class="td1">Всего с доставкой</td>
		    <td class="td2" id="product_count_total">&nbsp;</td>
		    <td class="td2">&nbsp;</td>
		    <td class="td2" id="product_price_total_with_delivery">
		    	<?php 
		    		echo ($globalCost + $deliveryCost);
		    	?>
		    </td>
		    <td class="td2">&nbsp;</td>
		    <td class="td2">&nbsp;</td>
		</tr>
		<tr id="row_example" style="display:none;">
			<td class="td2 product_id product_added_id">&nbsp;</td>
			<td class="td1 product_name">&nbsp;</td>
			<td class="td2 product_count">
				<input style="width:20px;" type="text" class="product_count_input" name="product_callcenter_count[]" value="0" />
			</td>
			<td class="td2 product_price">&nbsp;</td>
			<td class="td2 product_sum">&nbsp;</td>
			<td class="td2 product_count_available">&nbsp;</td>
			<td class='td2'>
				<a href='#' class="product_delete" style='color:red;'>х</a>
				<input type="hidden" class="product_id_input" name="product_callcenter_id[]" value="" />
				
			</td>
		</tr>
	    </tfoot>
	</table>
    </fieldset>
    
    
<script type="text/javascript">
function calculateTotal()
{
	var arId = new Array();
	var i = 0;
	$('td.product_added_id').filter(":visible").each(function(){
		var prodId = parseInt($(this).text());
		arId[i] = prodId;
		i++
	});

	var $count = 0;
	var arCount = new Array();
	var c = 0;
	$("td.product_count").filter(":visible").each(function() {
		var $value = $(this).attr("count");
		$count = $count + parseInt($value);
		arCount[c] = $value;
		c++;
	});

	$("#product_count_total").text($count);
	//var $delCost = $('#product_delivery_sum').val();
	//alert($delCost);
	var $price = 0;
	$("td.product_sum").filter(":visible").each(function() {
		$price = $price + parseInt($(this).text());
	});

	var $inMkad = $("#inMkad").is(':checked') ? 1 : 2;
	var $city_value = $("#suggest_city").val();
    var totalCosts = $('#product_delivery_sum').html();
	if($price != 0 && $city_value && $inMkad){
	var urls = "/admin/call-center/deliverycosts/city/"+$city_value+"/in_city/"+$inMkad+"/sum/"+$price;
		$.ajax({
				url: urls,
				dataType: 'json',
				data:{productId:arId, productCount:arCount},
				success: function(data) {
						$("#delivery_cost").val(parseInt(data.result));
						$("#product_price_total_with_delivery").text($price + parseInt(data.result));
						$("#product_delivery_sum").text(parseInt(data.result));
				}
		});
	}
	<?php if($order->getId()){?>
		$("#product_price_total_with_delivery").text($price + <?php echo $deliveryCost; ?>);
	<?php }?>
	$("#product_price_total").text($price);
	
}

$(function() {
	
	$("#product_add").click(function() {
		var $id, $count;
		$id = $("#product_id").val();
		$count = parseInt($("#product_count").val());

		var $error = 0;
		if (!$id) {
			blinkField("#product_id");
			return false;
		}

		$("td.product_added_id").each(function() {
			var $self = $(this);
			var $value = $self.text();
			if ($value == $id) {
				$error = 1;
				blinkField($self);
			}
		});

		if ($error) {
			blinkField("#product_id");
			return false;
		}

		var $maxCount = parseInt($("#add_product_count").text());

		if (!$count || ($count > $maxCount)) {
			blinkField("#product_count");
			return false;
		}

		var $url = "/admin/call-center/product-info/id/" + $id;
		$.ajax({
			url: $url,
			dataType: 'json',
			success: function($product) {
				if ($product.result == 'failure') {
					blinkField("#product_id");
					blinkField("#product_name");
					$("#product_name").val("Неверный ID товара");
					return false;
				}

				if($product.reminder_name != 'null'){
					$(document).ready(function(){
					  	$("#reminderblock").show();
							var prod_name = '<li>'+$product.reminder_name+'</li>';
							$('#list_reminder').html($('#list_reminder').html() + prod_name);
					});
				}

				var $example = $("#row_example");
				var $new = $example.clone();
				$new.appendTo("#product_list");
				$new.removeAttr("id");
				$new.find(".product_id").text($product.id);
				$new.find(".product_name").text($product.name);
				$new.find(".product_count_available").text($product.count);
				$new.find(".product_count").find('input').val($count);
				$new.find(".product_count").attr('count', $count);
				$new.find(".product_price").text($product.price);
				$new.find(".product_sum").text($product.price * $count);
				
				$new.find(".product_id_input").val($product.id);
				$new.find(".product_count_input").val($count);

				$new.removeAttr("style");
				$("#product_id").val('');
				$("#product_count").val('');
				$("#product_name").val('');
				$("#add_product_count").text('');
				$("#add_product_price").text('');

				calculateTotal();
			}
		});
		

		
		return false;
	});


	var changeCountTimeout = null;
	$("input.product_callcenter_count_add").live('keyup', function() {
		var $self = $(this);
		var $value = parseInt($self.val());
			if(!($self.val()>0) && $self.val()!=""){
				$self.val(1);
				return true;
			}
	});
	
	
	$("input.product_count_input").live('keyup', function() {
		
		
		
		if (changeCountTimeout != null) {
			clearTimeout(changeCountTimeout);
			changeCountTimeout = null;
		}

		var $self = $(this);
		changeCountTimeout = setTimeout(function() {
			var $td = $self.parent();
			var $tr = $td.parent();
	
			var $countAvailable = parseInt($tr.find(".product_count_available").text());
			var $value = parseInt($self.val());
			if(!($self.val()>0)){
				$self.val(1);
				return true;
			}
			if (($countAvailable < $value) || !$value) {
				blinkField($self);
				return false;
			}
	
			$td.attr("count", $value);
			var $price = parseInt($tr.find(".product_price").text());
			$tr.find(".product_sum").text($price * $value);
			calculateTotal();
		}, 500);
	});

	$("a.product_delete").live("click", function() {

		if (!confirm('Вы уверены?')) {
			return false;
		}
		var del_name = $(this).parent('td').parent('tr').find('td.td1').text();
		
		$('#list_reminder li').each(function(){
			
			if(del_name.toLowerCase() == $(this).text().toLowerCase()){
				$(this).hide();
			}
		});
		var q=0;
		if($('#list_reminder li:visible').size()==0)		
			$('#reminderblock').hide();
			
		var $row = $(this).parent().parent();
		var $id = $row.find("td").filter(":first").text();
		$("#form_cc").append("<input type='hidden' name='product_callcenter_delete[]' value='"+$id+"' />")
		
		$row.remove();
		calculateTotal();

		return false;
	});

	var suggestTimeout = null;
	$("input.crud_form_suggest").live('keyup', function() {
		if (suggestTimeout != null) {
			clearTimeout(suggestTimeout);
			suggestTimeout = null;
		}
		
		var $self = $(this);
		var $value = $self.val();
		if (!$value) return;

		var $id = $self.attr('id');
		var $data = $id + '=' + $value;
		if ($id == 'suggest_street') {
			$data += '&city_id=' + $("#suggest_city").attr("rel");
		}
		suggestTimeout = setTimeout(function() {
			var $url = '/admin/call-center/suggest';
			$.ajax({ 
				url: $url, 
				type: 'post',
				data: $data,
				context: document.body,
				success: function(html) {
		        	if (html == '') {
		        		$(".suggest_result").hide();
			        	blinkField($self);
			        	return false;
		        	}

		        	$result = $self.next();
		        	$result.html(html);
		        	$result.show();
		    	}
			});
		}, 650);
			
		return;
	});

	$("li.suggest_item").live('click', function() {
		var $self = $(this);
		$("#product_name").val($self.text());
		$("#product_id").val($self.attr("rel"));
		$("#add_product_count").text($self.attr("count"));
		$("#add_product_price").text($self.attr("price"));
		$self.parent().parent().hide();
	});

	$("li.suggest_item_street").live('click', function() {
		var $self = $(this);
		$("#suggest_street").val($self.text());
		$self.parent().parent().hide();
	});

	$("body").click(function() {
		if (!$(this).hasClass('suggest_item')) {
			$(".suggest_result").hide();
		}
	});


	$("#add_comment").click(function() {
		var $url = $(this).attr('url');
		var $comment = $("#operator_comment").val();
		$.post($url, {operator_comment: $comment}, function($data) {
			$("#comments").html($data);
			$("#operator_comment").val("");
		});
	});

	$("input").keydown(function(event) {
		if(event.keyCode==13) {
			return false;
		}
	});

	function inMkadIsActive() {
		var $inMkad = $("#inMkad");
		var $metro = $("#metroId");
		var $value = $("#suggest_city").val();
		
		/*if (($value == 'Москва') || ($value == 'москва')) {
			$inMkad.removeAttr("disabled");
			$metro.removeAttr("disabled");
		} else {
			$inMkad.attr('checked', false);
			$inMkad.attr("disabled", "disabled");
			$metro.attr("disabled", "disabled");
			$metro.val('');
		}*/
	}

	inMkadIsActive();
	$("#suggest_city").keyup(inMkadIsActive);
	$("li.suggest_item_city").live('click', function() {
		var $self = $(this);
		$("#suggest_city").attr("rel", $self.attr('rel'));
		$("#suggest_city").val($self.text());
		$self.parent().parent().hide();
		inMkadIsActive();
	});

	$("#executed_at").datepicker({
		dateFormat: 'dd.mm.yy',
		minDate: "+1"
	});
});


function blinkField(fld) {
    fld = $(fld);
    if (fld.data('blink_timer'))
        clearInterval(fld.data('blink_timer'));
 
    var blink_count = 6;
 
    fld.data('blink_timer', setInterval(function() {
        fld.toggleClass('field_warning');
        if (blink_count-- < 0) {
            fld.removeClass('field_warning');
            clearInterval(fld.data('blink_timer'));
        }
    }, 100));
}


</script>

<style type="text/css">
.field_warning {
	border: 1px red solid;
}

.suggest_result {
	text-align: left;
	position: absolute;
	width: 300px;
	height: 200px;
	overflow-y: scroll;
	overflow-x: hidden;
	background-color: white;
	border: 2px black solid;
	display: none;
}

.suggest_item:hover, .suggest_item_street:hover, .suggest_item_city:hover {
	cursor: pointer;
	background-color: #d6ffd6;
}
</style>
    
    